package com.example.blogsystem.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoder;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import lombok.val;
import org.junit.jupiter.api.Test;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {
    private static String secreString="/+A4ORppH1UzQVulxtH0Y3+Mlk8yQGcEhg4dsN8CcUc=";
    private static Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secreString));
    @Test
    public void genJWT() {

        Map<String,Object> data = new HashMap<>();
        data.put("id",5);
        data.put("name","zhangsan");
        String compact = Jwts.builder()
                .setClaims(data)
                .signWith(key)
                .compact();
        System.out.println(compact);
    }
    @Test
    void genKey(){
        SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        String encode = Encoders.BASE64.encode(secretKey.getEncoded());
        System.out.println(encode);
    }
    @Test
    void verify(){
        String token ="eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiemhhbmdzYW4iLCJpZCI6NX0.Kocj0W5HxPjLyegbuwvNm-wwbjptAb71a86hEKl381M";
        JwtParser build = Jwts.parser().setSigningKey(key).build();
        Claims body = build.parseClaimsJws(token).getBody();
        System.out.println(body.get("id"));
        System.out.println(body.get("name"));
    }
}
